# coding=utf-8
import xlrd
import os
import time
import datetime


class Tools():

    def __init__(self):
        os.popen("adb devices")
        self.exitVersion = 0

    def getgmsVersion(self):
        '''
        :return: 获取GMS pacakge的版本号 android版本号_年月
        字段获取方法： adb shell  “getprop | grep ro.com.google.gmsversion”
                    回显: [ro.com.google.gmsversion]: [10_202009]
        提示：在windows中过滤是findstr，Linux中的过滤是grep
        '''
        Version = os.popen("adb shell getprop | findstr ro.com.google.gmsversion ").read()
        #输出样式[ro.com.google.gmsversion]: [10_202009]
        Versionmsg = Version.split(":")[1].split("[")[1].split("]")[0].strip()
        return Versionmsg


    def getSecurityPatch(self):
        '''
        :return: 获取security_patch 安全补丁日期 日期 年-月-日
        字段获取方法 ： adb shell  “getprop | grep ro.vendor.build.security_patch”
                    回显: [ro.vendor.build.security_patch]: [2020-12-05]
        '''
        patch = os.popen("adb shell  getprop | findstr ro.vendor.build.security_patch").read()
        #patch输出样式 ：[ro.vendor.build.security_patch]: [2020-12-05]
        patchmsg = patch.split(":")[1].split("[")[1].split("]")[0].strip()
        return patchmsg


    def readExcelGMS(self):
        self.filename = "./excelFile/version.xlsx"
        xl = xlrd.open_workbook('{}'.format(self.filename))
        table = xl.sheet_by_name("GMSSversion")
        # 获取一共多少行
        rows = table.nrows
        # #获取一共有多少列
        # cols = table.ncols
        #读取所有gms的版本号，添加到一个列表里面
        gmslist = []
        self.gmsVersion = self.getgmsVersion()   #获取当前设备上的GMS pacakge的版本号
        # print(type(gmsVersion),gmsVersion,"gmsVersion")
        for i in range(1,rows):
            gmslist.append(table.cell(i, 1).value)
            if self.gmsVersion in gmslist:
                #如果当前表格中存在该版本，则输出该版本对应的有效截止日期
                validityDate = table.cell(i,2).value
                self.exitVersion = 1
                return validityDate
        if self.gmsVersion not in gmslist:
                msg = "当前表格中无该GMSversion版本：{}".format(self.gmsVersion)
                print(msg)
        # print(gmslist)




    def readExcelPatch(self):
        xl = xlrd.open_workbook('{}'.format(self.filename))
        table = xl.sheet_by_name("security_patch")

    def getNowTime(self):
        NowTime = datetime.datetime.now().strftime("%Y-%m-%d") #获取当前日期2021-01-05
        return  NowTime

    def getTwoMonthsAgoDate(self):
        #获取当前日期2021-01-05 往前加60天
        # TwoMonthsAgoDate = (datetime.datetime.now()+datetime.timedelta(days=-60)).strftime("%Y-%m-%d")
        #获取当前月的前两个月即可
        NowTime = datetime.datetime.today()
        NowYear = NowTime.year
        NowMonth = NowTime.month
        if NowMonth == 1:
            NowYear = NowYear -1
            TWOMonthAgo = 11

        elif NowMonth == 2:
            NowYear = NowYear - 1
            TWOMonthAgo = 12

        else:
            TWOMonthAgo = NowMonth - 2

        TwoMonthsAgoDate = datetime.date(NowYear,TWOMonthAgo,1).strftime("%Y-%m")
        #当前月的，前两个月的月份
        # print(TwoMonthsAgoDate)
        # print(TwoMonthsAgoDate)
        return TwoMonthsAgoDate

    def versionDateJudge(self):
        self.readExcelGMS()
        if self.exitVersion == 1:
            validityDate = self.readExcelGMS() #有效日期
            validityDate = validityDate.replace(".","-")
            validityDate = time.strptime(validityDate, "%Y-%m-%d")
            validityDateTime = int(time.mktime(validityDate))
            # print(validityDateTime)

            nowDate = self.getNowTime()  #获取当前时间
            nowDate = time.strptime(nowDate, "%Y-%m-%d")   #把当前字符串转换为时间戳
            # print(nowDate)
            nowDateTime = int(time.mktime(nowDate))  #，返回这是秒
            # print(nowDateTime)

            leadTime =  validityDateTime - nowDateTime  #到期时间减去当前时间，若为正数则未过期，若未负数则过期

            if leadTime > 0 :
                print("当前设备GMSversion未到期,该版本到期时间为:{}".format(self.getNowTime()))
            elif leadTime == 0:
                print("当前设备GMSversion今天到期,当前版本为：{}".format(self.gmsVersion))
            else:
                print("当前设备GMSversion已过期,当前版本为：{},版本到期时间为：{}".format(self.gmsVersion,self.readExcelGMS()))

        elif self.exitVersion == 0:
            pass

    def patchJudge(self):

        #获取安全补丁的日期时间，并转化为时间戳
        SecurityPatchDate = self.getSecurityPatch()
        # SecurityPatchDate = time.strptime(SecurityPatchDate,"%Y-%m-%d")
        # print(SecurityPatchDate,"--------------")
        SecurityPatchDate = SecurityPatchDate[0:7] #取到月份
        # print(SecurityPatchDate,"#############")
        SecurityPatchDate = time.strptime(SecurityPatchDate,"%Y-%m")
        FormatSecurityPatchDate = int(time.mktime(SecurityPatchDate)) #转换为时间戳，秒

        #获取当前时间往前推60天（两个月）的时间，并转化为时间戳
        TwoMonthsAgoDate = self.getTwoMonthsAgoDate()
        # TwoMonthsAgoDate = time.strptime(TwoMonthsAgoDate,"%Y-%m-%d")
        TwoMonthsAgoDate = time.strptime(TwoMonthsAgoDate,"%Y-%m")
        # print(TwoMonthsAgoDate)
        FormatTwoMonthsAgoDate = int(time.mktime(TwoMonthsAgoDate)) #转换为时间戳，秒

        #计算两个时间戳之间的差，如果安全补丁日期大于 TwoMonthsAgoDate ，那么则未过期，否则为过期
        leadTime = FormatSecurityPatchDate - FormatTwoMonthsAgoDate

        if leadTime > 0:
            print("当前设备security_patch版本{}，未过期，请放心使用！".format(self.getSecurityPatch()))

        elif leadTime == 0 | leadTime < 0  :
            print("当前设备security_patch版本{}，已过期！请及时更新！".format(self.getSecurityPatch()))






if __name__ == '__main__':
    run = Tools()
    run.versionDateJudge()
    run.patchJudge()

